<template>
  <div class="video-container">
    <!-- 视频播放器 -->
    <video ref="videoPlayer" class="video-js vjs-default-skin" controls muted>
      <source :src="videoSrc" type="video/mp4" />
    </video>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, watch } from 'vue'
import videojs from 'video.js'
// 定义组件的 props
const props = defineProps({
  videoSrc: {
    type: String,
    required: true
  }
})

// 定义视频播放器的引用
const videoPlayer = ref(null)
let player = null

// 初始化视频播放器
onMounted(() => {
  if (videoPlayer.value) {
    player = videojs(videoPlayer.value, {
      controls: true,
      autoplay: false,
      preload: 'auto',
      muted: true, // 移动端静音自动播放
      fluid: true // 保持宽高比
    })
  }
})

// 销毁播放器以避免内存泄漏
onBeforeUnmount(() => {
  if (player) {
    player.dispose()
  }
})

// 监听 videoSrc 的变化，更新播放器的视频源
watch(
  () => props.videoSrc,
  (newSrc) => {
    if (videoPlayer.value && player) {
      player.src({ type: 'video/mp4', src: newSrc })
      player.load()
      player.pause()
    }
  }
)
</script>

<style scoped>
.video-container {
  /* 居中显示 */
  display: flex;
  flex-direction: column; /* 使内容垂直排列 */
  justify-content: center;
  align-items: center;
  /* 背景变黑 */
  background-color: #808080;
  /* 确保标志和视频播放器都在容器内 */
  position: relative;
  width: 100%;
}
.video-js {
  /* 视频播放器样式 */
  width: 100%;
  height: 100%;
}
</style>
